# frozen_string_literal: true

require 'leanweb'
require 'leanweb/controller_mixins/render_with_layout'

# Main controller is the default controller.
class MainController < LeanWeb::Controller
  include LeanWeb::ControllerMixins::RenderWithLayout

  def sign_post
    return render_with_layout('sign_error.haml') unless valid_sign_params?

    mail_signature
    render_with_layout('sign.haml')
  end

  def signup_post
    return render_with_layout('signup_error.haml') if
      any_param_empty?(%w[subject name email]) ||
      !params['challenge'].empty?

    mail_signup
    render_with_layout('signup.haml')
  end

  protected

  def any_param_empty?(param_keys)
    return true if params.nil?

    param_keys.each do |param|
      return true if !params.include?(param) || params[param].empty?
    end

    false
  end

  def valid_sign_params?
    params['challenge'].empty? && !params['email'].empty? &&
      (!params['name'].empty? || !params['org'].empty?)
  end

  def mail_signature
    require 'lean_mail'
    LeanMail.deliver(
      ENV.fetch('NOTIFICATION_EMAILS').split,
      "Firma #{params['subject']}",
      <<~MAIL
        Nombre y ocupación: #{params['name']}
        Organización: #{params['org']}
        Email: #{params['email']}
        Web o red social: #{params['web']}
        Comentarios:
        #{params['comments']}
      MAIL
    )
  end

  def mail_signup
    require 'lean_mail'
    LeanMail.deliver(
      ENV.fetch('NOTIFICATION_EMAILS').split,
      "Inscripción para #{params['subject']}",
      <<~MAIL
        Nombre o apodo: #{params['name']}
        Email: #{params['email']}
        Web o red social: #{params['web']}
        Recibir emails: #{params&.[]('mailing_list') ? 'Sí' : 'No'}
        Comentarios:
        #{params['comments']}
      MAIL
    )
  end

  def template_defaults
    {
      'md' => { with_toc_data: true },
      'org' => { setupfile: 'setup.org' }
    }
  end
end
